package com.example.aicloud.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.aicloud.entity.Discuss;
import com.example.aicloud.entity.User;
import com.example.aicloud.entity.vo.CommentVO;
import com.example.aicloud.entity.vo.DiscussVO;
import com.example.aicloud.service.ICommentService;
import com.example.aicloud.service.IDiscussService;
import com.example.aicloud.service.IUserService;
import com.example.aicloud.utils.Result;
import com.example.aicloud.utils.SecurityUtil;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 讨论表控制器
 *
 * @author Mr.Tang
 * @date 2024-07-27
 */
@RestController
@RequestMapping("/discuss")
@AllArgsConstructor
public class DiscussController {

    private final IDiscussService discussService;

    private final ThreadPoolTaskExecutor threadPool;

    private final IUserService userService;

    private final ICommentService commentService;

    /**
     * 查询讨论详情
     */
    @RequestMapping("/detail")
    public Result detail(Long did) throws ExecutionException, InterruptedException {
        if (did == null || did <= 0) {
            return Result.fail("参数错误");
        }
        Discuss discuss = discussService.getById(did);
        if (discuss == null || discuss.getDid() < 0) {
            return Result.fail("话题不存在");
        }
        // 任务一： 查询 discuss 中的 username, 让 阅读量 +1
        threadPool.submit(() -> {
           // 1. 更新数据库
            discussService.updateReadCount(did);
           // 2. 设置返回对象的阅读数+1
            discuss.setReadCount(discuss.getReadCount() + 1);
        });
        CompletableFuture<DiscussVO> task1 = CompletableFuture.supplyAsync(() -> {
            // 对象转换
            DiscussVO discussVO = BeanUtil.toBean(discuss, DiscussVO.class);
            User user = userService.getById(discuss.getUid());
            if (user != null && user.getUid() > 0) {
                discussVO.setUsername(user.getUsername());
            }
            return discussVO;
        }, threadPool);
        // 任务二： 查询 discuss 所对应的 comment 列表
        CompletableFuture<List<CommentVO>> task2 = CompletableFuture.supplyAsync(() -> {
            return commentService.getCommentList(did);
        }, threadPool);

        // 等待两个任务执行完成
        CompletableFuture.allOf(task1, task2);
        HashMap<String, Object> result = new HashMap<>();
        result.put("discuss", task1.get());
        result.put("commentList", task2.get());

        return Result.success(result);
    }

    /**
     * 添加话题讨论
     */
    @RequestMapping("/save")
    public Result save(@Validated Discuss discuss) {
        discuss.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean save = discussService.save(discuss);
        if (!save) {
            return Result.fail("添加失败");
        }
        return Result.success();
    }

    /**
     * 获取我的讨论列表
     */
    @RequestMapping("/mylist")
    public Result getMyList() {
        return Result.success(discussService.list(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getUid, SecurityUtil.getCurrentUser().getUid())
                        .orderByDesc(Discuss::getDid)
        ));
    }

    /**
     * 删除话题
     */
    @RequestMapping("/delete")
    public Result delete(Long did) {
        if (did == null || did <= 0) {
            return Result.fail("参数错误");
        }
        boolean remove = discussService.remove(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getDid, did)
                        .eq(Discuss::getUid, SecurityUtil.getCurrentUser().getUid())
        );
        if (!remove) {
            return Result.fail("删除失败");
        }
        return Result.success();
    }


}
